package com.morningyet.bug.log4j2.attacker.controller;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

/**
 * 抽象父处理器
 *
 * @author moringyet
 */
public abstract class AbstractHandler {

    /**
     * 获取制定类的字节码文件路径
     * @return 字节码文件路径
     */
    public static String getBytecodeFilePath(Class<? extends Object> clazz) {
        String canonicalName = clazz.getCanonicalName();
        return canonicalName.replaceAll("\\.", "/").concat(".class");
    }

    /**
     * 输出字节码
     */
    protected void outputBytecode(HttpServletResponse response, Class<? extends Object> clazz) throws IOException {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        InputStream inputStream = classLoader.getResourceAsStream(AbstractHandler.getBytecodeFilePath(clazz));
        ServletOutputStream outputStream = response.getOutputStream();

        int count;
        byte[] bytes = new byte[512];

        while ((count = inputStream.read(bytes)) > 0) {
            outputStream.write(bytes, 0, count);
        }
        outputStream.flush();
        outputStream.close();
    }

}
